// server/src/controllers/categoryController.ts
import { Request, Response } from 'express'
import { prisma } from '../lib/prisma'
import { sendSuccess, sendError } from '../utils/response'

export const getCategories = async (req: Request, res: Response) => {
  try {
    const categories = await prisma.category.findMany({
      orderBy: [
        { sortOrder: 'asc' },
        { createdAt: 'desc' }
      ],
      include: {
        _count: {
          select: {
            contents: {
              where: {
                isPublished: true
              }
            }
          }
        }
      }
    })

    sendSuccess(res, { categories })
  } catch (error) {
    console.error('Get categories error:', error)
    sendError(res, '获取分类列表失败')
  }
}

export const getCategory = async (req: Request, res: Response) => {
  try {
    const { id } = req.params

    const category = await prisma.category.findUnique({
      where: { id: parseInt(id) },
      include: {
        _count: {
          select: {
            contents: {
              where: {
                isPublished: true
              }
            }
          }
        }
      }
    })

    if (!category) {
      return sendError(res, '分类不存在', 404)
    }

    sendSuccess(res, { category })
  } catch (error) {
    console.error('Get category error:', error)
    sendError(res, '获取分类详情失败')
  }
}

export const createCategory = async (req: Request, res: Response) => {
  try {
    const { name, slug, displayName, description, sortOrder } = req.body

    if (!name || !slug || !displayName) {
      return sendError(res, '请填写所有必填字段')
    }

    // 检查分类名或别名是否已存在
    const existingCategory = await prisma.category.findFirst({
      where: {
        OR: [
          { name },
          { slug }
        ]
      }
    })

    if (existingCategory) {
      return sendError(res, '分类名或别名已存在')
    }

    const category = await prisma.category.create({
      data: {
        name,
        slug,
        displayName,
        description,
        sortOrder: sortOrder || 0
      }
    })

    sendSuccess(res, { category }, '分类创建成功')
  } catch (error) {
    console.error('Create category error:', error)
    sendError(res, '分类创建失败')
  }
}

export const updateCategory = async (req: Request, res: Response) => {
  try {
    const { id } = req.params
    const { name, slug, displayName, description, sortOrder } = req.body

    // 检查分类是否存在
    const existingCategory = await prisma.category.findUnique({
      where: { id: parseInt(id) }
    })

    if (!existingCategory) {
      return sendError(res, '分类不存在', 404)
    }

    // 检查分类名或别名是否与其他分类冲突
    if (name || slug) {
      const conflictingCategory = await prisma.category.findFirst({
        where: {
          AND: [
            { id: { not: parseInt(id) } },
            {
              OR: [
                ...(name ? [{ name }] : []),
                ...(slug ? [{ slug }] : [])
              ]
            }
          ]
        }
      })

      if (conflictingCategory) {
        return sendError(res, '分类名或别名与其他分类冲突')
      }
    }

    const category = await prisma.category.update({
      where: { id: parseInt(id) },
      data: {
        ...(name && { name }),
        ...(slug && { slug }),
        ...(displayName && { displayName }),
        ...(description !== undefined && { description }),
        ...(sortOrder !== undefined && { sortOrder: parseInt(sortOrder) })
      }
    })

    sendSuccess(res, { category }, '分类更新成功')
  } catch (error) {
    console.error('Update category error:', error)
    sendError(res, '分类更新失败')
  }
}

export const deleteCategory = async (req: Request, res: Response) => {
  try {
    const { id } = req.params

    // 检查分类是否存在
    const existingCategory = await prisma.category.findUnique({
      where: { id: parseInt(id) },
      include: {
        _count: {
          select: {
            contents: true
          }
        }
      }
    })

    if (!existingCategory) {
      return sendError(res, '分类不存在', 404)
    }

    // 检查分类下是否有内容
    if (existingCategory._count.contents > 0) {
      return sendError(res, '该分类下存在内容，无法删除')
    }

    await prisma.category.delete({
      where: { id: parseInt(id) }
    })

    sendSuccess(res, null, '分类删除成功')
  } catch (error) {
    console.error('Delete category error:', error)
    sendError(res, '分类删除失败')
  }
}